/**
 * 运单管理服务
 * 基于LeanCloud进行运单数据的CRUD操作
 */

import { dataAPI } from '@/http/leancloud';

export interface WaybillData {
  objectId?: string;
  cargoNo: string;
  waybillNo?: string;
  orderId?: any;
  senderName: string;
  senderPhone: string;
  senderAddress: string;
  receiverName: string;
  receiverPhone: string;
  receiverAddress: string;
  cargoType: string;
  totalQuantity: number;
  totalVolume: number;
  totalWeight: number;
  paymentMethod: number; // 1预付 2到付 3月结
  declaredValue: number;
  insuranceFee: number;
  deliveryFee: number;
  unloadingFee: number;
  totalFreight: number;
  operator: string;
  operatorPhone: string;
  orderTime: Date;
  driverId?: string;
  driverPhone?: string;
  route: string;
  vehiclePlate?: string;
  departureStationId?: string;
  transferStationId?: string;
  arrivalStationId?: string;
  status: number; // 0待配载 1已配载 2已发车 3运输中 4已送达 5已签收 6已取消
  assignedTime?: Date;
  departureTime?: Date;
  arrivalTime?: Date;
  signTime?: Date;
}

export interface WaybillQueryParams {
  cargoNo?: string;
  waybillNo?: string;
  senderInfo?: string;
  receiverInfo?: string;
  status?: number;
  paymentMethod?: number;
  departureStation?: string;
  destinationStation?: string;
  transferStation?: string;
  startDate?: string;
  endDate?: string;
  driverPhone?: string;
  vehicleNo?: string;
  page?: number;
  pageSize?: number;
}

/**
 * 运单服务类
 */
export class WaybillService {
  private static readonly CLASS_NAME = 'Order';

  /**
   * 查询运单列表
   */
  static async getWaybillList(params: WaybillQueryParams = {}) {
    try {
      const query: any = {};
      
      // 构建查询条件
      if (params.cargoNo) {
        query.cargoNo = { $regex: params.cargoNo };
      }
      if (params.waybillNo) {
        query.orderNo = { $regex: params.waybillNo };
      }
      if (params.senderInfo) {
        query.$or = [
          { senderName: { $regex: params.senderInfo } },
          { senderPhone: { $regex: params.senderInfo } },
          { senderAddress: { $regex: params.senderInfo } }
        ];
      }
      if (params.receiverInfo) {
        query.$or = [
          { receiverName: { $regex: params.receiverInfo } },
          { receiverPhone: { $regex: params.receiverInfo } },
          { receiverAddress: { $regex: params.receiverInfo } }
        ];
      }
      if (params.status !== undefined) {
        query.status = params.status;
      }
      if (params.paymentMethod !== undefined) {
        query.paymentMethod = params.paymentMethod;
      }
      if (params.startDate && params.endDate) {
        query.orderTime = {
          $gte: new Date(params.startDate),
          $lte: new Date(params.endDate)
        };
      }

      const data = await dataAPI.query(this.CLASS_NAME, query);
      return {
        success: true,
        data: data.map(this.formatWaybillData),
        total: data.length
      };
    } catch (error) {
      console.error('查询运单列表失败:', error);
      return { success: false, error, data: [], total: 0 };
    }
  }

  /**
   * 获取待配载运单
   */
  static async getUnassignedWaybills(params: WaybillQueryParams = {}) {
    return await this.getWaybillList({ ...params, status: 0 });
  }

  /**
   * 获取已配载运单
   */
  static async getAssignedWaybills(params: WaybillQueryParams = {}) {
    try {
      const query: any = { status: { $in: [1, 2, 3, 4, 5] } }; // 已配载及后续状态
      
      if (params.vehicleNo) {
        query.vehiclePlate = { $regex: params.vehicleNo };
      }
      if (params.driverPhone) {
        query.driverPhone = { $regex: params.driverPhone };
      }
      
      const data = await dataAPI.query(this.CLASS_NAME, query);
      return {
        success: true,
        data: data.map(this.formatWaybillData),
        total: data.length
      };
    } catch (error) {
      console.error('查询已配载运单失败:', error);
      return { success: false, error, data: [], total: 0 };
    }
  }

  /**
   * 配载运单
   */
  static async assignWaybill(waybillId: string, assignData: {
    driverId: string;
    driverPhone: string;
    vehiclePlate: string;
  }) {
    try {
      const updateData = {
        ...assignData,
        status: 1,
        assignedTime: new Date()
      };
      
      await dataAPI.save(this.CLASS_NAME, {
        objectId: waybillId,
        ...updateData
      });
      
      return { success: true };
    } catch (error) {
      console.error('配载运单失败:', error);
      return { success: false, error };
    }
  }

  /**
   * 批量配载运单
   */
  static async batchAssignWaybills(waybillIds: string[], assignData: {
    driverId: string;
    driverPhone: string;
    vehiclePlate: string;
  }) {
    try {
      const promises = waybillIds.map(id => 
        this.assignWaybill(id, assignData)
      );
      
      await Promise.all(promises);
      return { success: true };
    } catch (error) {
      console.error('批量配载运单失败:', error);
      return { success: false, error };
    }
  }

  /**
   * 确认发车
   */
  static async confirmDeparture(waybillId: string) {
    try {
      await dataAPI.save(this.CLASS_NAME, {
        objectId: waybillId,
        status: 2,
        departureTime: new Date()
      });
      
      return { success: true };
    } catch (error) {
      console.error('确认发车失败:', error);
      return { success: false, error };
    }
  }

  /**
   * 取消运单
   */
  static async cancelWaybill(waybillId: string, reason?: string) {
    try {
      await dataAPI.save(this.CLASS_NAME, {
        objectId: waybillId,
        status: 6,
        cancelReason: reason,
        cancelTime: new Date()
      });
      
      return { success: true };
    } catch (error) {
      console.error('取消运单失败:', error);
      return { success: false, error };
    }
  }

  /**
   * 格式化运单数据
   */
  private static formatWaybillData(item: any): WaybillData {
    return {
      objectId: item.objectId,
      cargoNo: item.cargoNo || '',
      waybillNo: item.orderNo || '',
      senderName: item.senderName || '',
      senderPhone: item.senderPhone || '',
      senderAddress: item.senderAddress || '',
      receiverName: item.receiverName || '',
      receiverPhone: item.receiverPhone || '',
      receiverAddress: item.receiverAddress || '',
      cargoType: item.cargoType || '',
      totalQuantity: item.totalQuantity || 0,
      totalVolume: item.totalVolume || 0,
      totalWeight: item.totalWeight || 0,
      paymentMethod: item.paymentMethod || 1,
      declaredValue: item.declaredValue || 0,
      insuranceFee: item.insuranceFee || 0,
      deliveryFee: item.deliveryFee || 0,
      unloadingFee: item.unloadingFee || 0,
      totalFreight: item.totalFreight || 0,
      operator: item.operator || '',
      operatorPhone: item.operatorPhone || '',
      orderTime: item.orderTime ? new Date(item.orderTime) : new Date(),
      driverId: item.driverId || '',
      driverPhone: item.driverPhone || '',
      route: item.route || '',
      vehiclePlate: item.vehiclePlate || '',
      status: item.status || 0,
      assignedTime: item.assignedTime ? new Date(item.assignedTime) : undefined,
      departureTime: item.departureTime ? new Date(item.departureTime) : undefined,
      arrivalTime: item.arrivalTime ? new Date(item.arrivalTime) : undefined,
      signTime: item.signTime ? new Date(item.signTime) : undefined
    };
  }

  /**
   * 获取状态文本
   */
  static getStatusText(status: number): string {
    const statusMap: { [key: number]: string } = {
      0: '待配载',
      1: '已配载',
      2: '已发车',
      3: '运输中',
      4: '已送达',
      5: '已签收',
      6: '已取消'
    };
    return statusMap[status] || '未知状态';
  }

  /**
   * 获取付款方式文本
   */
  static getPaymentMethodText(method: number): string {
    const methodMap: { [key: number]: string } = {
      1: '预付',
      2: '到付',
      3: '月结'
    };
    return methodMap[method] || '未知';
  }
}